package spring;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.util.ClassUtils;

/**
 * @author 1203056
 * @version Id: ResourceUtils.java, v 0.1 2021-09-04 10:50 1203056 Exp $
 */
public class MyResourceUtils {

    public static List<Class> scanClass(String basePackage) throws IOException, ClassNotFoundException {

        final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(basePackage) + '/' + DEFAULT_RESOURCE_PATTERN;
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] candidateResources = resourcePatternResolver.getResources(packageSearchPath);
        MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory();
        List<Class> classLists = new ArrayList<>();
        for (Resource resource : candidateResources) {

            if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                String className = metadataReader.getClassMetadata().getClassName();
                classLists.add(ClassUtils.getDefaultClassLoader().loadClass(className));
            }
        }
        return classLists;
    }
}
